<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * Logs DMLoggables to the system log.
 *
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */

class DMLogger {

	/** @var string */
	private $client_ip;
	/** @var PHP log priority constant */
	private $facility;
	/** @var PHP log facility constant */
	private $priority;
	/** @var DMURI */
	private $uri;

	public function __construct() {
		$this->setClientIP($_SERVER['REMOTE_ADDR']);
		$this->setFacility(LOG_USER);
		$this->setPriority(LOG_NOTICE);
		$this->setURI(DMHTTPRequest::getCurrent()->getURI());
	}

	/**
	 * @param DMLoggable obj
	 * @return void
	 */
	public function log(DMLoggable $obj) {
		if (!DMConfigXML::getInstance()->isLoggingEnabled()) {
			return;
		}

		if (stripos($_SERVER['SERVER_SOFTWARE'], 'microsoft') !== false) {
			// windows only supports LOG_USER
			openlog("dmBridge", LOG_ODELAY, LOG_USER);
		} else {
			openlog("dmBridge", LOG_ODELAY, $this->getFacility());
		}
		syslog($obj->getLogPriority(), $obj->getLogMessage());
		closelog();

		$obj->setHasBeenLogged(true);
	}

	/**
	 * @return string
	 */
	public function getClientIP() {
		return $this->client_ip;
	}

	/**
	 * @param string ip
	 * @throws DMIllegalArgumentException
	 */
	public function setClientIP($ip) {
		if (!DMString::isValidIPAddress($ip)) {
			throw new DMIllegalArgumentException(
				sprintf(DMLocalizedString::getString('INVALID_IP'), $ip));
		}
		$this->client_ip = $ip;
	}

	/**
	 * @return string
	 */
	public function getFacility() {
		return $this->facility;
	}

	/**
	 * @param const facility PHP log facility constant
	 */
	public function setFacility($facility) {
		$this->facility = $facility;
	}

	/**
	 * @return string
	 */
	public function getPriority() {
		return $this->priority;
	}

	/**
	 * @param const priority PHP log priority constant
	 */
	public function setPriority($priority) {
		$this->priority = $priority;
	}

	/**
	 * @return DMURI
	 */
	public function getURI() {
		return $this->uri;
	}

	/**
	 * @param DMURI uri
	 */
	public function setURI(DMURI $uri) {
		$this->uri = $uri;
	}

}
